<?php
declare (strict_types = 1);
/**
 * 素材模型
 */
namespace app\common\model;

use app\common\facade\model\PgmInfoModel;
use app\common\facade\model\PgmInfoPlanModel; // 节目库播出明细表
use think\facade\Db;

class PgmInfoDetail extends BaseModel
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 't_pgm_info_detail';

    public function pgmdetailList($where = [])
    {
        return self::where($where)->select()->toArray();
    }

    // 写入当日频道中固定节目明细
    public function addGuDingpgm($param)
    {
        $sql = "select * from t_pgm_info_play where 1=1";
        if (!empty($param['channel_id'])){
            $sql .= " AND channel_id=".$param['channel_id'];
        }
        if (!empty($param['date'])){
            $sql .= " AND ((all_avail=1 AND s_play_date <='".$param['date']."') OR (all_avail=0 AND s_play_date <='".$param['date']."' AND e_play_date >='".$param['date']."'))";
        }
        $list = Db::query($sql);
        foreach($list as $k => $v) {
            $arr = self::where([
                ['pgm_id', '=', $v['pgm_id']],
                ['play_id', '=', $v['play_id']],
                ['play_date', '=', $param['date']]
            ])->select()->toArray();
            if(empty($arr)) {
                // 查询当前日期是否设置固定节目集数
                $week = self::getDateWeek($param['date']);
                $planInfo = PgmInfoPlanModel::where([
                    ['pgm_id', '=', $v['pgm_id']],
                    ['play_id', '=', $v['play_id']],
                    ['dayofweek', '=', $week]
                ])->find()->toArray();

                if($planInfo['play_num'] > 0) { // 写入固定节目明细
                    $pgminfo = PgmInfoModel::where([['pgm_id', '=', $v['pgm_id']]])->find()->toArray();
                    if(empty($pgminfo) || $pgminfo['pgm_attr'] != '1' ){ continue; }  //  如果节目信息为空，或者不是固定节目跳出
                    $gudingInfo = self::createGudingDetail($pgminfo, $planInfo, $param['date']); // 写入固定节目
                    return self::addEditSave($gudingInfo);
                }
            }
        }
        return true;
    }

    public function createGudingDetail($pgminfo, $planInfo, $date)
    {
        return [
            'pgm_id' => $pgminfo['pgm_id'],
            'play_id' => $planInfo['play_id'],
            'play_num' => $planInfo['play_num'],
            'pgm_name' => $pgminfo['pgm_name'],
            'pgm_type' => $pgminfo['pgm_type'],
            'pgm_len' => $pgminfo['pgm_len'],
            'play_date' => $date,
            'play_time' => $planInfo['s_time'],
            'pgm_attr' => $pgminfo['pgm_attr'],
            'mat_id' => 0,
            'tape_code' => '',
            'tc_type' => '',
            'markin' => 0,
            'markout' => 0
        ];
    }

    public function getDateWeek($date)
    {
        $weekarray = [7,1,2,3,4,5,6];
        return $weekarray[date('w', strtotime($date))];
    }

    // 根据频道ID，日期获取节目信息
    public function pgmInfoDayList($param)
    {
        $sql = "select * from t_pgm_info_play where 1=1";
        if (!empty($param['channel_id'])) {
            $sql .= " AND channel_id=".$param['channel_id'];
        }
        if (!empty($param['date'])){
            $sql .= " AND ((all_avail=1 AND s_play_date <='".$param['date']."') OR (all_avail=0 AND s_play_date <='".$param['date']."' AND e_play_date >='".$param['date']."'))";
        }
        $list = Db::query($sql);
        $data = [];
        foreach($list as $k => $v) {
            $arr = [];
            $arr = self::findDayList($v, $param['date']); // 查找当天，当前频道的播放节目.
            $data = array_merge($data, $arr);
        }
        return [
            "list" => $data,
            "total" => count($data)
        ];
    }

    public function findDayList($arr, $date) {
        $where = [];
        $field = '*';
        $where[] = ['pgm_id', '=', $arr['pgm_id']];
        $where[] = ['play_id', '=', $arr['play_id']];
        $where[] = ['play_date', '=', $date];

        $list = self::with([
            'matTypeHasOne' => function ($query) {
                $query->withField(['mat_type_id','mat_type_name'])->hidden(['mat_type_id']);
            },
            'pgmInfoHanOne' => function ($query) {
                $query->withField(['pgm_id','pgm_attr'])->hidden(['pgm_id']);
            },
        ])->field($field)->where($where)->select()->toArray();

        foreach($list as $k =>$v) {
            if($v['matTypeHasOne'] != null) {
                $list[$k]['pgm_type_name'] = $v['matTypeHasOne']['mat_type_name'];                               
            } else {
                $list[$k]['pgm_type_name'] = null;
            }

            if($v['pgmInfoHanOne'] != null) {
                $list[$k]['pgm_attr'] = $v['pgmInfoHanOne']['pgm_attr'];                               
            } else {
                $list[$k]['pgm_attr'] = null;
            }
            unset($list[$k]['matTypeHasOne']);
            unset($list[$k]['pgmInfoHanOne']);
        }
        return $list; 
    }

    public function matTypeHasOne()
    {
        return $this->hasOne(MatType::class, 'mat_type_id', 'pgm_type');
    }

    public function pgmInfoHanOne() 
    {
        return $this->hasOne(PgmInfo::class, 'pgm_id', 'pgm_id');
    }
}
